package com.zhangshuo.test1.controller;
import com.sun.net.httpserver.HttpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

import java.util.HashMap;

/**
 * Created by Administrator on 2017/6/2 0002.
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCacheManager redisCacheManager;

    @RequestMapping("/set")
    public Object set( @RequestParam() String key ,
                       @RequestParam() Object value){
        Map<String,Object> data = new HashMap<>();
        data.put("data",value);
        redisTemplate.opsForValue().set(key,data);
        return "操作成功";
    }

    @RequestMapping("/get")
    public Object get(
            @RequestParam() String key){
        Map<String,Object> result = new HashMap<>();
        result.put("value",redisTemplate.opsForValue().get(key));
        return result;
    }


    @RequestMapping("/testCache")
    public Object getCacheByName(){
        Cache cache = redisCacheManager.getCache("oneDay");
        cache.put("test","test");
        return "操作成功";
    }


    @RequestMapping("/testSession")
    public Object testSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name","张三");
        session.setAttribute("age",10);
        String name = (String) session.getAttribute("name");
        return name;
    }

    @RequestMapping("/testSessionGet/{attributeName}")
    public Object testSessionGet(@PathVariable() String attributeName, HttpSession session){
        return session.getAttribute(attributeName);
    }

    @RequestMapping("/testSessionDel")
    public String testSessionDel(HttpSession session){
        session.invalidate();
        return "清除成功";
    }

}
